/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年8月13日
 */
package com.massyframework.beanskin.maven.plugin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.maven.artifact.versioning.ComparableVersion;
import org.apache.maven.model.Dependency;


/**
 * 依赖匹配
 * @author huangkh
 *
 */
public class DependencyChecker {
	
	private static final String COLON = ":";
	
	private Map<String, Dependency> dependencyMap;

	/**
	 * 构造方法
	 * @param dependencies {@link List}
	 */
	public DependencyChecker(List<Dependency> dependencies) {
		this.dependencyMap = new HashMap<>();
		for (Dependency dependency: dependencies) {
			this.dependencyMap.put(this.getKey(dependency), dependency);
		}
	}

	/**
	 * 是否不存在
	 * @param dependency {@link Dependency}
	 * @return {@link boolean}, 不存在则返回{@code true},存在返回{@code false}
	 */
	public boolean isNotExist(Dependency dependency) {
		String key = this.getKey(dependency);
		Dependency exists = this.dependencyMap.get(key);
		if (exists != null) {
			//比较谁的版本高			
			ComparableVersion existsVersion = new ComparableVersion(exists.getVersion());
			ComparableVersion version = new ComparableVersion(dependency.getVersion());
			
			
			if (existsVersion.compareTo(version) <0) {
				this.dependencyMap.put(key, dependency);
				return true;
			}
			return false;
		}else {
			this.dependencyMap.put(key, dependency);
			return true;
		}
	}
	
	/**
	 * 从{@link Depdendency}中提取key
	 * @param dependency
	 * @return
	 */
	protected String getKey(Dependency dependency) {
		return dependency.getGroupId().concat(COLON).concat(dependency.getArtifactId());
	}
}
